package mtn.bowen.yan.server.controller;

import com.jfoenix.controls.JFXComboBox;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.FileChooser;
import mtn.bowen.yan.server.common.Constant;
import mtn.bowen.yan.server.enums.DishesKindEnum;
import mtn.bowen.yan.server.enums.DishesTypeEnum;
import mtn.bowen.yan.server.fx.StageManager;
import mtn.bowen.yan.server.model.PictureDishes;
import mtn.bowen.yan.server.service.MainService;
import mtn.bowen.yan.server.service.MenuManagementService;
import mtn.bowen.yan.server.service.PictureDishesService;
import mtn.bowen.yan.server.utils.LoadingUtils;
import mtn.bowen.yan.server.utils.Platform;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

/**
 * @author <a href=mailto:yanbowen90@foxmail.com> bowen.yan </a>
 * @version 1.0
 * @description: 管理菜品
 * @date 2021-10-28 7:35 AM
 */
@Component
public class MenuManagementController extends BaseController implements Initializable {

    private final static Logger LOGGER = LoggerFactory.getLogger(MenuManagementController.class);

    /**
     * 添加菜品种类选择
     */
    @FXML
    private JFXComboBox addRecipeComboBox;

    /**
     * 删除菜品种类选择
     */
    @FXML
    private JFXComboBox deleteRecipeComboBox;

    @FXML
    private HBox introduceHBox;

    @FXML
    private StackPane stackPane;

    @FXML
    private TextArea introduceText;

    @Resource
    private MenuManagementService menuManagementService;

    @FXML
    private TextField dishesName;

    @FXML
    private TextField chefName;

    @Resource
    private LoadingUtils loadingUtils;

    @Resource
    private MainService mainService;

    @Resource
    private PictureDishesService pictureDishesService;

    @FXML
    private VBox allKindPictureVBox;

    @FXML
    private HBox allKindPictureHBox;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        try {
            //选择类型
            DishesTypeEnum type = DishesTypeEnum.getDishesType(StageManager.getTypeAndWeekMap("Type"));
            //选择类型
            addRecipeComboBox.getSelectionModel().select(type.getCode() - 1);
            //选择类型
            deleteRecipeComboBox.getSelectionModel().selectFirst();

            introduceText.prefWidthProperty().bind(stackPane.widthProperty());
            introduceText.setFont(Font.font("KaiTi", FontWeight.NORMAL, 16));

            allKindPictureVBox.prefWidthProperty().bind(stackPane.widthProperty());
            //allKindPictureHBox.prefHeightProperty().bind(stackPane.heightProperty());// <!--prefHeight="580.0"-->

            //按种类更新全部菜品UI
            menuManagementService.changeUI(allKindPictureHBox, deleteRecipeComboBox);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("MenuManagementController.initialize is error", e);
        }
    }

    @FXML
    private void choosePicture() {
        try {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择菜品图片");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("图片类型", "*.jpg", "*.png")
            );
            //单选
            //File pictureFile = fileChooser.showSaveDialog(new Stage());
            File pictureFile = fileChooser.showOpenDialog(StageManager.getStage("saveEditorDiary"));
            if (pictureFile != null) {
                StageManager.putFoodPictures("pictureFile", pictureFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("MenuManagementController.choosePicture is error", e);
        }
    }

    @FXML
    private void submitPicture() {
        //名称检查
        String dishesNameText = dishesName.getText().trim();
        int length = dishesNameText.trim().length();
        if (StringUtils.isBlank(dishesNameText)) {
            menuManagementService.showDialog("添加菜品错误", "菜品名称不能为空！", Alert.AlertType.ERROR);
            return;
        }
//        if (length > Constant.LENGTH_OF_DISHES) {
//            menuManagementService.showDialog("添加菜品错误", "菜品名称不能超过5个汉字！", Alert.AlertType.ERROR);
//            return;
//        }
        String chefNameText = chefName.getText().trim();
        if (StringUtils.isBlank(chefNameText)) {
            menuManagementService.showDialog("添加菜品错误", "大厨名称不能为空！", Alert.AlertType.ERROR);
            return;
        }
        File file = StageManager.getFoodPictures("pictureFile");

        if (mainService.checkFile(file)) {
            menuManagementService.showDialog("添加菜品错误", "请添加菜品图片！", Alert.AlertType.ERROR);
            return;
        }

        //开始执行Loading界面、并设置解除等待标记
        StageManager.putParentLoadMap("ParentLoad", loadingUtils.loadingDefault(StageManager.getParentStackPaneMap("parentStackPane")));
        StageManager.getExecutor().execute(() -> {
            //食谱种类记录
            int indexKind = addRecipeComboBox.getSelectionModel().getSelectedIndex();
            String kind = DishesKindEnum.getDishesKind(indexKind + 1).getMsg();
            String uuid = UUID.randomUUID().toString().replace("-", "");

            String uuidName = menuManagementService.savePicture(file, uuid);
            String trim = introduceText.getText().trim();
            PictureDishes build = PictureDishes.builder().uuid(uuidName).name(dishesNameText).kind(indexKind + 1).chef(chefNameText).introduce(trim).build();
            pictureDishesService.savePictureDishes(build);

            //停止界面1.25秒
            menuManagementService.loadShowTime();

            System.out.println("indexKind: " + kind);
            Platform.runLater(() -> {
                dishesName.clear();
                chefName.clear();
                introduceText.clear();
                loadingUtils.remove(StageManager.getParentStackPaneMap("parentStackPane"), StageManager.getParentLoadMap("ParentLoad"));
                menuManagementService.showDialog("添加菜品成功", "添加【" + kind + "】 【" + dishesNameText + "】 成功！", Alert.AlertType.INFORMATION);
                //按种类更新全部菜品UI
                menuManagementService.changeUI(allKindPictureHBox, addRecipeComboBox);
            });
        });
    }

    /**
     * 按种类显示全部菜品
     */
    @FXML
    private void deleteRecipe() {
        menuManagementService.changeUI(allKindPictureHBox, deleteRecipeComboBox);
    }

    /**
     * 删除菜品
     */
    @FXML
    private void deletePicture() {
        menuManagementService.deletePicture(allKindPictureHBox, deleteRecipeComboBox);
        ;
    }
}
